/*
 * Copyright:Copyright(c)2017-2020
 * Company:ygego
 */
package com.example.springbootelasticjob.config;

import com.dangdang.ddframe.job.api.JobOperateAPI;
import com.dangdang.ddframe.job.api.JobSettingsAPI;
import com.dangdang.ddframe.job.api.JobStatisticsAPI;
import com.dangdang.ddframe.job.domain.ServerInfo;
import com.dangdang.ddframe.job.executor.ShardingContexts;
import com.dangdang.ddframe.job.lite.api.listener.AbstractDistributeOnceElasticJobListener;
import com.google.common.base.Optional;
import org.apache.zookeeper.Op;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;

/**
 * ClassName: MyElasticJobListener
 * Description:
 * Author: zhaojinpeng
 * Date: 2018/6/8 16:15
 * History:
 * <zhaojinpeng> <2018/6/8 16:15> <1.0>    <desc>
 * 作者姓名 修改时间    版本号 描述
 */
public class MyElasticJobListener extends AbstractDistributeOnceElasticJobListener {

    @Autowired
    private JobOperateAPI jobOperateAPI;
    @Autowired
    private JobStatisticsAPI jobStatisticsAPI;

    @Value("${spring.elasticjob.zookeeper.server-lists}")
    private String connectString;

    public MyElasticJobListener(long startedTimeoutMilliseconds, long completedTimeoutMilliseconds) {
        super(startedTimeoutMilliseconds, completedTimeoutMilliseconds);
    }

    @Override
    public void doBeforeJobExecutedAtLastStarted(ShardingContexts shardingContexts) {

    }

    @Override
    public void doAfterJobExecutedAtLastCompleted(ShardingContexts shardingContexts) {

        String jobName = shardingContexts.getJobName();
        Collection<ServerInfo> servers = jobStatisticsAPI.getServers(jobName);
        servers.forEach(server -> jobOperateAPI.remove(Optional.of(server.getJobName()), Optional.of(server.getIp())));

    }
}
